//
//  config.m
//  Stock_Pro
//
//  Created by imuse on 10-11-18.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "config.h"

#import "FileTools.h"
#import "StringTools.h"

/************************************************************************/
/*								应用配置相关								*/
/************************************************************************/
XML_NODE *g_pXmlNodeConfig;

char	*g_ConfigXml = NULL;

void ReadConfig()
{
	FreeConfig();
	
	FILE_DATA *pFile = FileTools_ReadDataEx("config.data");
	char *p = pFile->pData;
	g_pXmlNodeConfig = XmlTools_Encrypt(&p);
	FileTools_FreeData(pFile);
}

void FreeConfig()
{
	if (g_pXmlNodeConfig) {
		XmlTools_Free(g_pXmlNodeConfig);
		g_pXmlNodeConfig = NULL;
	}
}

void SaveConfig()
{
	char sBuf[4096];
	char sTemp[4096];
	memset(sBuf, 0, sizeof(sBuf));
	memset(sTemp, 0, sizeof(sTemp));
	XML_NODE *pNode;
	pNode = g_pXmlNodeConfig;
	while (pNode) {
		/*容错处理*/
        if(pNode->pChildNode)
        {
            sprintf(sTemp, "%s<%s>%s</%s>", sBuf, pNode->pName, pNode->pChildNode->pName, pNode->pName);
        }
        else
        {
            sprintf(sTemp, "%s<%s></%s>", sBuf, pNode->pName, pNode->pName);
        }
		strcpy(sBuf, sTemp);
		pNode = pNode->pNextNode;
	}
	/*写入配置*/
	FileTools_WriteDataEx("config.data", sBuf, strlen(sBuf));
}

void AddConfig(char *pTag, char *pVar)
{
    /*容错处理*/
    if (pTag == NULL || pVar == NULL || strlen(pTag) == 0) {
		return;
	}
	XML_NODE *pNodeLast;
	pNodeLast = g_pXmlNodeConfig;
	while (pNodeLast->pNextNode) {
		pNodeLast = pNodeLast->pNextNode;
	}
	
	XML_NODE *pTemp = XmlTools_GetLeafNode(g_pXmlNodeConfig, pTag);
	
	if (pTemp) {
		//tag
		//		Tools_Free(&pTemp->pName);
		//		pTemp->pName = Tools_Malloc(strlen(pTag)+2);
		//		strcpy(pTemp->pName, pTag);
		//		pTemp->hash = ELFHash(pTemp->pName);
		//var
        if(pTemp->pChildNode)
        {
            //有变量值节点
            pTemp = pTemp->pChildNode;
            Tools_Free(&pTemp->pName);
            pTemp->pName = Tools_Malloc(strlen(pVar)+2);
            strcpy(pTemp->pName, pVar);
            pTemp->hash = ELFHash(pTemp->pName);
        }
        else
        {
            //没有变量节点，创建变量节点
            XML_NODE *pNodeVar = Tools_Malloc(sizeof(XML_NODE));
            pNodeVar->pName = Tools_Malloc(strlen(pVar)+2);
            strcpy(pNodeVar->pName, pVar);
            pNodeVar->hash = ELFHash(pNodeVar->pName);
            
			//            //插入节点，这里要连接前后节点
			//            if(pTemp->pNextNode)
			//            {
			//                XML_NODE *pNextNode = pTemp->pNextNode;
			//                pNodeVar->pNextNode = pNextNode;
			//                pNextNode->pPrevNode = pNodeVar;
			//            }
            
            pTemp->pChildNode = pNodeVar;
            pNodeVar->pParentNode = pTemp;
            
        }
		return;
	}
	
	XML_NODE *pNodeTag = Tools_Malloc(sizeof(XML_NODE));
	pNodeTag->pName = Tools_Malloc(strlen(pTag)+2);
	strcpy(pNodeTag->pName, pTag);
	pNodeTag->hash = ELFHash(pNodeTag->pName);
	
	XML_NODE *pNodeVar = Tools_Malloc(sizeof(XML_NODE));
	pNodeVar->pName = Tools_Malloc(strlen(pVar)+2);
	strcpy(pNodeVar->pName, pVar);
	pNodeVar->hash = ELFHash(pNodeVar->pName);
	
	pNodeTag->pChildNode = pNodeVar;
	pNodeVar->pParentNode = pNodeTag;
	
	pNodeLast->pNextNode = pNodeTag;
	pNodeTag->pPrevNode = pNodeLast;
	
}

char* GetConfig(char *pTag)
{
	return XmlTools_GetLeafNodeText(g_pXmlNodeConfig, pTag);
}


/************************************************************************/
/*								界面布局相关								*/
/************************************************************************/

void AutoConfigLayout(UIView *uiView, XML_NODE *pNode, char *pViewName, int nMode)
{
//	pNode = XmlTools_GetLeafNodeChild(pNode, pViewName);
//	
//	
//	
//	if( nMode==UIDeviceOrientationLandscapeLeft || nMode==UIDeviceOrientationLandscapeRight)
//	{
//		//向左旋转
//		pNode = XmlTools_GetLeafNodeChild(pNode, "l");
//	}
//	else
//	{
//		//上或下
//		pNode = XmlTools_GetLeafNodeChild(pNode, "t");
//		
//	}
//	
//	
//	pNode = XmlTools_GetLeafNodeChild(pNode, "item");
//	
//	int nID = 0;
//	while(pNode)
//	{
//		
//		CGRect frame = CGRectMake(_a2i(XmlTools_GetOptionValue(pNode->pOption, "l")),
//								  _a2i(XmlTools_GetOptionValue(pNode->pOption, "t")),
//								  _a2i(XmlTools_GetOptionValue(pNode->pOption, "w")),
//								  _a2i(XmlTools_GetOptionValue(pNode->pOption, "h")));
//		nID = _a2i(XmlTools_GetOptionValue(pNode->pOption, "id"));
//		UIView *view = [uiView viewWithTag: nID];
//		if (view!=nil) {
//			view.frame = frame;
//			if (nID!=QUOT_L2CL_WEBV_ID 
//				&& nID!=QUOT_L2CL_TIT1_ID
//				&& nID!=FIND_VIEW_LABE_ID
//				&& nID!=FIND_VIEW_TEXF_ID
//				&& nID!=FIND_VIEW_NOTE_ID
//				&& nID!=FIND_VIEW_NOTX_ID
//				&& nID!=FIND_VIEW_LIST_ID
//				&& nID!=OWNM_VIEW_TABV_ID) {
//        if ([view respondsToSelector:@selector(OnChangeView:)]) {
//          [view OnChangeView:nMode];
//        }
//			}
//		}
//		
//		pNode = XmlTools_GetLeafNodeNext(pNode, "item");
//	}
}

/************************************************************************/
/*								板块配置相关								*/
/************************************************************************/
/*板块配置*/
XML_NODE *g_pXmlNodeBlack;

void ReadBlackData()
{
	FILE_DATA *pFile = FileTools_ReadDataEx("block.data");
	char *p = pFile->pData;
	g_pXmlNodeBlack = XmlTools_Encrypt(&p);
	FileTools_FreeData(pFile);
}

void FreeBlackData()
{
	XmlTools_Free(g_pXmlNodeBlack);
}

XML_NODE* GetXmlNodeBlack()
{
	return g_pXmlNodeBlack;
}

/************************************************************************/
/*								服务地址相关								*/
/************************************************************************/
/*服务器地址*/
XML_NODE *g_pXmlNodeServer;
void ReadServerUrl()
{
	/*释放旧的*/
	FreeServerUrl();
	
	FILE_DATA *pData = FileTools_ReadDataEx("server.data");
	char *p = pData->pData;
	g_pXmlNodeServer = XmlTools_Encrypt(&p);
	FileTools_FreeData(pData);
}

void FreeServerUrl()
{
	if (g_pXmlNodeServer) {
		XmlTools_Free(g_pXmlNodeServer);
		g_pXmlNodeServer = NULL;
	}
}

char* GetUrl(char *pTag, int nType)
{
	char *pRet;
    char *pTemp;
	
    pRet = Tools_Malloc(MAX_PATH*2);

    pTemp = XmlTools_GetLeafNodeText(g_pXmlNodeServer, pTag);
    if(pTemp)
    {
        strcpy(pRet, pTemp);
    }
    
	if (strestr(pTag, URL_QUOTE)) {
		/*行情地址*/
		char *pHost;
		char *pBuf;
		TBOOL bFind;
		char sHost[MAX_PATH];
		ROW_NODE *pRow;
		COL_NODE *pCol;
		ROW_NODE *pTemp;
		
		//使用leve 1主站查询对应服务器地址
		pHost = GetConfig(CONFIG_HOST);
		memset(sHost, 0, sizeof(sHost));
		
		pBuf = Tools_Malloc(strlen(pRet)+2);
		strcpy(pBuf, pRet);
		
		pTemp = pRow = StringSplitRowCol(pBuf, ',', '|');
		bFind = FALSE;
		while (pTemp) {
			pCol = pTemp->node;
			pCol = pCol->next;
			if (strstr(pCol->text, pHost)) {
				/*找到*/
				if (nType==URL_TYPE_LEVE2) {
					strcpy(pRet, pCol->next->text);
				}
				else {
					strcpy(pRet, pCol->text);
				}
				//保存leve 1主站地址
				StringTools_GetRightString(pCol->text, sHost, "http://", ":");
				AddConfig(CONFIG_HOST, sHost);
				bFind = TRUE;
				break;
			}
			pTemp = pTemp->next;
		}
		if (!bFind) {
			//没找到配置中的地址，山随机选择个
			int nPos;
			int nCount = GetRowCount(pRow);
      if (nCount > 0) {//过滤掉如果状态控制中没有配置地址
        int nIndex = abs(arc4random());
        nIndex = nIndex%nCount;
        pTemp = pRow;
        nPos = 0;
        while (pTemp) {
          if (nIndex==nPos) {
            pCol = pTemp->node;
            pCol = pCol->next;
            if (nType==URL_TYPE_LEVE2) {
              strcpy(pRet, pCol->next->text);
            }
            else {
              strcpy(pRet, pCol->text);
            }
            //保存leve 1主站地址
            StringTools_GetRightString(pCol->text, sHost, "http://", ":");
            AddConfig(CONFIG_HOST, sHost);
            break;
          }
          nPos++;
          pTemp = pTemp->next;
        }

      }
						
		}
		FreeRowNode(&pRow);
		Tools_Free(&pBuf);
		//保存配置
		SaveConfig();
	}
	
	StringTools_DeleteString(pRet, strlen(pRet), "amp;");
	return pRet;
}

char* GetQuoteIP(char *pTag, int nType)
{
	char *pIP;
	char *p = GetUrl(URL_QUOTE, nType);
	pIP = Tools_Malloc(MAX_PATH);
	StringTools_GetRightString(p, pIP, "http://", ":");
	Tools_Free(&p);
	return pIP;
}

ROW_NODE* GetUrlNode(char *pTag)
{
	ROW_NODE *pRow;
	char	*pBuf;
	pBuf = XmlTools_GetLeafNodeText(g_pXmlNodeServer, pTag);
	//printf("\n buf:%s",pBuf);
	pRow = StringSplitRowCol(pBuf, ',', '|');
	return pRow;
}

void UrlAddUserInfo(char* pUrl)
{
    char *pUser;
    char *pSession;
    char *pMobile;
    char temp[128];
    memset(temp, 0, sizeof(temp));
    
    pUser = GetConfig(CONFIG_USER_ID);
    pSession = GetConfig(CONFIG_SESSION_ID);
    pMobile = GetConfig(CONFIG_USER_PHONE);
  
    if(!pUser)
    {
        pUser = temp;
    }
    if(!pSession)
    {
        pSession = temp;
    }
    if (!pMobile) {
      pMobile = temp;
    }
  
  
  int nFlag = StringTools_FindSubString(pUrl, strlen(pUrl), "?", 1);
	if (nFlag > 0 || StringTools_FindSubString(pUrl, strlen(pUrl), "http://", 7) == -1) {
    if (nFlag == strlen(pUrl)-1) {
      sprintf(pUrl,"%sclientversion=%s&userid=%s&sessionid=%s&mobile=%s", pUrl, APP_VER, pUser, pSession,pMobile);
    }else{
      sprintf(pUrl,"%s&clientversion=%s&userid=%s&sessionid=%s&mobile=%s", pUrl, APP_VER, pUser, pSession,pMobile);
    }
	}else{
		sprintf(pUrl,"%s?clientversion=%s&userid=%s&sessionid=%s&mobile=%s", pUrl, APP_VER, pUser, pSession,pMobile);
	}
}

char* ReadConfigLayoutXml()
{
	if (g_ConfigXml == NULL) {
        
    FILE_DATA *pFile = NULL;
    
    if(IPHONE5){
      pFile = FileTools_ReadDataEx("layout_iphone5.data");
    }else{
      if (IOS7_OR_LATER) {
        pFile = FileTools_ReadDataEx("layout_iphone4.data");
      }else{
        pFile = FileTools_ReadDataEx("layout.data");
      }
    }
    
		g_ConfigXml = (char *)Tools_Malloc(pFile->nSize + 1);
		strcpy(g_ConfigXml, pFile->pData);
		FileTools_FreeData(pFile);
	}
	
	return g_ConfigXml;
}

